package com.yunkeji.system.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunkeji.common.core.domain.PageQuery;
import com.yunkeji.common.core.page.TableDataInfo;
import com.yunkeji.common.exception.ServiceException;
import com.yunkeji.common.msg.PushMessage;
import com.yunkeji.dao.domain.AppUser;
import com.yunkeji.dao.domain.SysMsgLog;
import com.yunkeji.dao.mapper.AppUserMapper;
import com.yunkeji.dao.mapper.SysMsgLogMapper;
import com.yunkeji.dao.vo.SysMsgLogVo;
import com.yunkeji.system.service.ISysMsgLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 后台系统消息发送记录业务层处理
 *
 * @author 雷擎宇
 * @date 2024-11-14
 */
@RequiredArgsConstructor
@Service
public class SysMsgLogServiceImpl implements ISysMsgLogService {

    private final SysMsgLogMapper baseMapper;
    private final AppUserMapper userMapper;

    @Override
    public TableDataInfo<SysMsgLogVo> queryPageList(SysMsgLog bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysMsgLog> lqw = buildQueryWrapper(bo);
        Page<SysMsgLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysMsgLog> buildQueryWrapper(SysMsgLog log) {
        LambdaQueryWrapper<SysMsgLog> lqw = Wrappers.lambdaQuery();
        lqw.like(log.getPlatformId() != null, SysMsgLog::getPlatformId, log.getPlatformId());
        lqw.like(log.getContent() != null, SysMsgLog::getContent, log.getContent());
        lqw.eq(log.getType() != null, SysMsgLog::getType, log.getType());
        lqw.orderByDesc(SysMsgLog::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insert(SysMsgLog log) {
        boolean flag = true;
        if (log.getType() == 6) {
            long count = userMapper.selectCount(Wrappers.lambdaQuery(AppUser.class)
                .eq(AppUser::getAccountType, 1)
                .eq(AppUser::getStatus, 0)
                .eq(AppUser::getPlatformId, log.getPlatformId()));
            if(count <= 0){
                throw new ServiceException("请输入正确的爱洞ID");
            }
            flag = false;
        }
        List<Long> to = flag ? userMapper.queryPlatformIds(log.getType()) : ListUtil.of(log.getPlatformId());
        PushMessage.sendSysNotifyBatch(to, log.getContent());
        baseMapper.insert(log);
        return true;
    }

}
